﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using TcpServer.ThreadManage;
using TcpServer.Global;
using TcpServer.User;
using System.IO;
using System.IO.Ports;
using TcpServer.Dao;


namespace TcpServer
{
    class Program
    {
        public static bool local;
        public static List<UserClass> UserList = new List<UserClass>();
        public static List<ServerClient> SerList = new List<ServerClient>();
        public static TcpListener MyListener;
        public static TcpListener MyListener2;
        public static TcpListener MyListener3;
        public static TcpListener MyListener4;
        public static TcpListener MyListener5;

        public static TcpListener MyListener6;      //12348端口，进N39数据库
        public static TcpListener MyListener7;      //12349端口，进n40数据库

        public static TcpListener CMDListener;


        static void Main(string[] args)
        {

            Console.WriteLine("准备开启程序");

            //开启客户端链接端口
            MyListener = new TcpListener(new IPEndPoint(IPAddress.Any, 10086));
            MyListener.Start();
            Console.WriteLine("开始监听10086端口");
            Thread listenThread = new Thread(new ThreadStart(ListenerThread.ListenClientConnect));
            listenThread.IsBackground = true;
            listenThread.Start();

            //开启客户端链接端口
            MyListener2 = new TcpListener(new IPEndPoint(IPAddress.Any, 12345));
            MyListener2.Start();
            Console.WriteLine("开始监听12345端口");
            Thread listenThread2 = new Thread(new ThreadStart(ListenerThread.ListenClientConnect2));
            listenThread2.IsBackground = true;
            listenThread2.Start();

            //开启客户端链接端口
            MyListener3 = new TcpListener(new IPEndPoint(IPAddress.Any, 12346));
            MyListener3.Start();
            Console.WriteLine("开始监听12346端口");
            Thread listenThread3 = new Thread(new ThreadStart(ListenerThread.ListenClientConnect3));
            listenThread3.IsBackground = true;
            listenThread3.Start();

            //开启客户端链接端口
            MyListener5 = new TcpListener(new IPEndPoint(IPAddress.Any, 12344));
            MyListener5.Start();
            Console.WriteLine("开始监听12344端口");
            Thread listenThread5 = new Thread(new ThreadStart(ListenerThread.ListenClientConnect5));
            listenThread5.IsBackground = true;
            listenThread5.Start();

            //开启客户端链接端口
            MyListener4 = new TcpListener(new IPEndPoint(IPAddress.Any, 12347));
            MyListener4.Start();
            Console.WriteLine("开始监听12347端口");
            Thread listenThread4 = new Thread(new ThreadStart(ListenerThread.ListenClientConnect4));
            listenThread4.IsBackground = true;
            listenThread4.Start();

            //开启客户端链接端口
            MyListener6 = new TcpListener(new IPEndPoint(IPAddress.Any, 12348));
            MyListener6.Start();
            Console.WriteLine("开始监听12348端口");
            Thread listenThread6 = new Thread(new ThreadStart(ListenerThread.ListenClientConnect6));
            listenThread6.IsBackground = true;
            listenThread6.Start();

            //开启客户端链接端口
            MyListener7 = new TcpListener(new IPEndPoint(IPAddress.Any, 12349));
            MyListener7.Start();
            Console.WriteLine("开始监听12349端口");
            Thread listenThread7 = new Thread(new ThreadStart(ListenerThread.ListenClientConnect7));
            listenThread7.IsBackground = true;
            listenThread7.Start();





            //开启服务器端链接端口
            CMDListener = new TcpListener(new IPEndPoint(IPAddress.Any, 10085));
            CMDListener.Start();
            Console.WriteLine("开始监听10085端口");
            Thread CMDListenThread = new Thread(new ThreadStart(ListenerThread.ListenCMDConnect));
            CMDListenThread.IsBackground = true;
            CMDListenThread.Start();


            //开启连接超时的值守线程
            Console.WriteLine("开启连接超时的值守线程，单片机连接10分钟不通信会被移除，命令端连接10分钟不通信会被移除");
            Thread CheckTimeOutThread = new Thread(new ThreadStart(ListenerThread.CheckConnctTimeOut));
            CheckTimeOutThread.IsBackground = true;
            CheckTimeOutThread.Start();

            //开启心跳包
            Console.WriteLine("开启心跳包，发送到本机的10084端口");
            Thread HeartBeatThread = new Thread(new ThreadStart(ListenerThread.HeartBeat));
            HeartBeatThread.IsBackground = true;
            HeartBeatThread.Start();

            //SerialPort com;
            //com = new SerialPort();
            //com.BaudRate = 12000;
            //com.PortName = "COM20";
            //com.DataBits = 8;
            //com.Open();
            //byte[] txdata = { 0xdd };
            //com.Write(txdata, 0, 1);
            ConsoleKeyInfo key;
            while (true)
            {
                key = Console.ReadKey(true);    //true参数是为了不显示在控制台上
                if (key.KeyChar == 'q' || key.KeyChar == 'Q')
                {
                    Console.WriteLine("read to exit!!!");
                    Thread.Sleep(1000);
                    break;

                }
                if (key.KeyChar == 'a' || key.KeyChar == 'A')
                {
                    //UserList[0].SendData("测试数据发送\r\n");
                    string sql = "";
                    sql += "begin";
                    sql += " TRUNCATE TABLE YejunCurrentTcp;";
                    sql += " INSERT INTO YejunCurrentTcp(MeterIP,LastConnectTime) SELECT * FROM (";
                    for (int i = 0; i < UserList.Count; i++)
                    {
                        if (i != 0)
                        {
                            sql += " union all";
                        }
                        sql += " select '" + UserList[i].MeterIP.ToString() + "' as MeterIP,'" + UserList[i].LastConnTime.ToString("yyyy-MM-dd HH:mm:ss") + "' as LastConnectTime";
                    }
                    sql += ") a end";

                    if (UserList.Count > 0)
                    {
                        BaseDao.execute(sql);
                        Console.WriteLine("已经把当前的TCP连接刷新到表YejunCurrentTcp");
                    }
                    else
                    {
                        BaseDao.execute("truncate table yejuncurrenttcp");
                        Console.WriteLine("当前没有连接,已经把当前的TCP连接刷新到表YejunCurrentTcp");
                    }
                    
                    



                }
                //com.Write(txdata, 0, 1);
                Thread.Sleep(1000);
            }

        }




    }



    ////Console.Write("Waiting for a client\r\n");
    ////Console.ReadLine();

    //mylis = new TcpListener(new IPEndPoint(IPAddress.Any, 5566)); 
    ////定义接收数据长度变量
    //int recv;
    ////定义接收数据的缓存
    //byte[] data = new byte[1024];
    ////定义侦听端口
    //IPEndPoint ipEnd = new IPEndPoint(IPAddress.Any, 5566);
    ////定义套接字类型
    //Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    ////连接
    //socket.Bind(ipEnd);
    ////开始侦听
    //socket.Listen(10);
    ////控制台输出侦听状态
    //Console.Write("Waiting for a client");
    ////一旦接受连接，创建一个客户端
    //Socket client = socket.Accept();
    ////获取客户端的IP和端口
    //IPEndPoint ipEndClient = (IPEndPoint)client.RemoteEndPoint;
    ////输出客户端的IP和端口
    //Console.Write("Connect with {0} at port {1}", ipEndClient.Address, ipEndClient.Port);
    ////定义待发送字符
    //string welcome = "Welcome to my server";
    ////数据类型转换
    //data = Encoding.ASCII.GetBytes(welcome);
    ////发送
    //client.Send(data, data.Length, SocketFlags.None);
    //while (true)
    //{
    //    //对data清零
    //    data = new byte[1024];
    //    //获取收到的数据的长度
    //    recv = client.Receive(data);
    //    //如果收到的数据长度为0，则退出
    //    if (recv == 0)
    //        break;
    //    //输出接收到的数据
    //    Console.Write(Encoding.ASCII.GetString(data, 0, recv));
    //    //将接收到的数据再发送出去
    //    client.Send(data, recv, SocketFlags.None);
    //}
    //Console.Write("Disconnect form{0}", ipEndClient.Address);
    //client.Close();
    //socket.Close();

    //MyThread3 t1 = new MyThread3("this is t1");
    //MyThread3 t2 = new MyThread3("this is t2");
    //MyThread3 t3 = new MyThread3("this is t3");

    //Thread th1 = new Thread(new ThreadStart(t1.Test1));
    //Thread th2 = new Thread(new ThreadStart(t2.Test1));
    //Thread th3 = new Thread(new ThreadStart(t3.Test1));
    //th1.Start();
    //Thread.Sleep(200);
    //th2.Start();
    //th3.Start();



    //Thread.Sleep(20000);
    //MyThread1 t = new MyThread1(15000);

    //t.RunThread();
    //System.Threading.Thread.Sleep(1000);
    //Console.WriteLine("线程状态" + t.ThreadHandle.ThreadState.ToString());
    //t.ThreadHandle.Suspend();
    //Console.WriteLine("线程状态" + t.ThreadHandle.ThreadState.ToString());
    //if (t.ThreadHandle.IsAlive)
    //{
    //    t.ThreadHandle.Abort();
    //}
    //else
    //{
    //    t.ThreadHandle.Resume();
    //}
    //GlobalClass myGlobal = new GlobalClass();
    //myGlobal.AddFunc();

    //GlobalClass myGlobal2 = new GlobalClass();
    //myGlobal2.AddFunc();
    //Console.WriteLine("main global value is "+ GlobalClass.g_Count1.ToString());

    //local = false;
    //Console.WriteLine("main local is " + local.ToString());

    //Thread.Sleep(100);
    //Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " begin stop thread");
    ////t.StopThread();
    //Thread.Sleep(100);
    //Console.WriteLine("main查看 MyThread1 线程状态" + t.ThreadHandle.ThreadState.ToString());
    //Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " thread stoped");

    //Console.WriteLine("main global value is " + myGlobal.ShowValue());
    //Console.WriteLine("main global2 value is " + myGlobal2.ShowValue());


    //Console.ReadKey();





}
